package org.example.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

@Component
@Slf4j
public class PdfToString {
    public String pdfToString(String filePath) {
        try (PDDocument document = PDDocument.load(new File(filePath))) {
            // 检查文件是否加密
            if (document.isEncrypted()) {
                throw new IOException("加密的PDF文件无法读取");
            }

            PDFTextStripper stripper = new PDFTextStripper();
            // 设置读取范围（可选）
            stripper.setStartPage(1);
            stripper.setEndPage(document.getNumberOfPages());

            // 获取文本内容
            return stripper.getText(document);
        } catch (IOException e) {
            throw new RuntimeException("PDF文件读取失败: " + e.getMessage(), e);
        }
    }
}
